from django.http import HttpResponse
#from django.shortcuts import render
from rest_framework.decorators import api_view
from ims.method import *
from ims.models import *
import datetime
import openpyxl
import xlrd
import xlwt
from thdata.sql import conn_ims
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
import sys
import uuid
import os
from django.conf import settings
import json
import base64
# from collections import OrderedDict
import datetime
import threading
import re
_mutex = threading.RLock()
# Create your views here.



@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def design_msgs(request):
    if request.method == "POST":
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        now = datetime.datetime.now()
        msg = TbDesignmessage()
        try:
            t_ver = set(TbDesignmessage.objects.filter(t_name=data["t_name"]).values_list("t_ver", flat=1))
            if data["t_ver"].strip() in t_ver:
                # content["status"] = 1
                raise Exception("刀具名稱和版次已存在！")
                # content["errmsg"] = "刀具名稱和版次已存在！"
                # return content
            msg.t_name = data["t_name"]
            msg.t_ver = data["t_ver"]
            msg.t_type = data["t_type"]
            msg.t_spec = data["t_spec"]
            msg.t_diam = data["t_diam"]
            msg.t_flen = data["t_flen"]
            msg.t_fnum = data["t_fnum"]
            msg.t_mmat = data["t_mmat"]
            msg.desi_id = request.user
            msg.last_name=request.user.last_name
            msg.desi_time = now
            msg.save()
            content["payload"] = {"toolt_id": msg.id, "t_name": msg.t_name, "t_ver": msg.t_ver, "t_type": msg.t_type,
                                  "t_spec": msg.t_spec, "t_diam": msg.t_diam, "t_flen": msg.t_flen,
                                  "t_fnum": msg.t_fnum,
                                  "t_mmat": msg.t_mmat}
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        return Response(content)
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": None}
        t_name = request.GET.get("t_name", None)
        page_num = request.GET.get("page", None)
        search = request.GET.get('search', None)
        if t_name:
            result = TbDesignmessage.objects.filter(t_name=t_name).order_by("-id").values()
        else:
            result = TbDesignmessage.objects.order_by("-id").values()
        if search:
            #print(search)
            search = str.lower(search)
            #print(search)
            _result = []
            for i in result:
                #print(i['t_name'])
                if search in str.lower(i['t_name'])\
                or search in str.lower(i['t_type']) \
                or search in str.lower(i['t_spec']) \
                or search in str(i['last_name']) \
                or search in str.lower(i['desi_id']):

                    _result.append(i)
            result = _result
        if page_num:
            pag_class = Paginator(result, 20)
        else:
            pag_class = Paginator(result, len(result) + 1)
            page_num = 1
        select_data = pag_class.page(page_num)
        content["payload"] = {"data": [], "page": {}}
        if select_data:
            for i in select_data:
                i["desi_time"] = i["desi_time"].strftime("%Y-%m-%d %H:%M:%S")
                content["payload"]["data"].append(i)
        content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                      'page_number': pag_class.page_range[-1]}
        return Response(content)

    if request.method == 'PUT':
        now = datetime.datetime.now()
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        try:
            if data:
                t_msg = TbDesignmessage.objects.filter(id=data['id'])
                t_msg.update(t_spec=data["t_spec"],
                             t_diam=data["t_diam"],
                             t_flen=data["t_flen"],
                             t_fnum=data["t_fnum"],
                             t_mmat=data["t_mmat"],
                             desi_id=str(request.user),
                             last_name=str(request.user.last_name),
                             desi_time=now)
                content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}

        try:
            id = request.GET.get("id", None)
            #data = request.data
            if not id:
                raise Exception("請傳入刀具id！")
            tb_pd = TbProductHead.objects.filter(toolt=id).values()
            if tb_pd:
                raise Exception("此刀具已有補正記錄，無法刪除")
            TbDesignmessage.objects.filter(id=id).delete()
            content['payload'].append("OK")

        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET"])
def design_msg(request, pk):
    if request.method == "GET":
        try:
            content = {"payload": {}, "status": 0, "errmsg": None}
            result = TbDesignmessage.objects.filter(id=pk).values()[0]
            content["payload"]["design_msg"] = result
            content["payload"]["wheel_msg"] = []
            content["payload"]["size_msg"] = []

            #now = datetime.datetime.now()
            wheel_msg = TbWheelmessage.objects.filter(t_name=result["t_name"], t_ver=result["t_ver"]).order_by('m_type',
                                                                                                               'w_no').values()
            if wheel_msg:
                for i in wheel_msg:
                    if i['desi_time']:
                        i['desi_time'] = i['desi_time'].strftime("%Y-%m-%d %H:%M:%S")

                    content["payload"]["wheel_msg"].append(i)

            #排序统一
            type_head_msg=TbCTypeHead.objects.filter(c_type=result["t_type"]).values()

            if type_head_msg:
                for i in type_head_msg:
                     type_body_msg=TbCTypeBody.objects.filter(c_type=i['id']).values('size_code','desc1')
                     if type_body_msg:
                         for j in type_body_msg:
                             TbDesignsize.objects.filter(d_code=j['size_code'],toolt=pk).update(desc1=j['desc1'])

            type_body_msg2 = TbCTypeBody.objects.filter(c_type=type_head_msg[0]['id']).values().order_by('desc1')
            #print(type_body_msg2)
            if type_body_msg2:
                for k in type_body_msg2:
                    #print(k['size_code'])


                    size_msg = TbDesignsize.objects.filter(t_name=result["t_name"], t_ver=result["t_ver"],d_code=k['size_code']).values()
                    # print(size_msg)
                    if size_msg:
                        for z in size_msg:
                            size_cot = {}
                            size_cot['status'] = k['status']
                            size_cot['context'] = k['context']

                            if z['desi_time']:
                                z['desi_time'] = z['desi_time'].strftime("%Y-%m-%d %H:%M:%S")


                            dictMerged2 = dict(z, **size_cot)

                            # if z['g_size'] or z['g_size']==0.0:
                            #     if len(str(z['g_size']).split('.')[1]) == 1 or len(str(z['g_size']).split('.')[1]) == 2:
                            #
                            #         if len(str(z['g_size']).split('.')[1]) == 1:
                            #             z['g_size'] = str(z['g_size']) + '00'
                            #             print(z['g_size'])
                            #
                            #         if len(str(z['g_size']).split('.')[1]) == 2:
                            #             z['g_size'] = str(z['g_size']) + '0'
                            #             print(z['g_size'])
                            #     else:
                            #         z['g_size'] = str(z['g_size'])
                                #print(z['g_size'])



                            content["payload"]["size_msg"].append(dictMerged2)
                    else:
                        # cutter_id = TbCTypeHead.objects.filter(c_type=result["t_type"]).values('id')
                        # if cutter_id:
                        #     result1 = TbCTypeBody.objects.filter(c_type_id=cutter_id[0]['id']).values()
                        #     for i in result1:
                        size_cot = {}
                        size_cot['t_name'] = result["t_name"]
                        size_cot['t_ver'] = result["t_ver"]
                        size_cot['d_code'] = k['size_code']
                        size_cot['grindingsite'] = k['size_name']
                        size_cot['g_type'] = k['g_type']
                        size_cot['status'] = k['status']
                        size_cot['context'] = k['context']
                        size_cot['desc1'] = k['desc1']
                        size_cot['toolt_id'] = pk
                        size_cot['g_size'] = None
                        size_cot['g_otol'] = None
                        size_cot['g_itol'] = None
                        size_cot['desi_id'] = None
                        size_cot['desi_time'] = None
                        size_cot['id'] = None
                        content["payload"]["size_msg"].append(size_cot)


        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def wheel(request, pk):
    if request.method == "POST":
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        try:
            now = datetime.datetime.now()
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')
            if t_msg:
                w_msg = TbWheelmessage()
                w_msg.t_name = t_msg[0]['t_name']
                w_msg.t_ver = t_msg[0]['t_ver']
                w_msg.w_no = data["w_no"]  # 砂輪序號
                w_msg.w_type = data["w_type"]  # 砂輪型號
                w_msg.w_feed = data["w_feed"]  # 砂輪粒度
                w_msg.w_speed = data["w_speed"]  # 砂輪轉速
                w_msg.w_gran = data["w_gran"]  # 砂輪進給
                w_msg.m_type = data["m_type"]  # 機台型號
                w_msg.w_station = data["w_station"]  # 砂輪磨削工位
                w_msg.toolt_id = pk
                w_msg.desi_id = request.user
                w_msg.last_name=request.user.last_name
                w_msg.desi_time = now
                w_msg.save()
            content["payload"].append(w_msg.id)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        result = TbWheelmessage.objects.filter(toolt=pk).order_by('m_type', 'w_no').values()
        if result:
            for i in result:
                content["payload"].append(i)
        return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            #data = request.data
            id = request.GET.get("id", None)
            if not id:
                raise Exception("請傳入砂輪id")
            TbWheelmessage.objects.filter(id=id).delete()
            content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "PUT":
        now = datetime.datetime.now()
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        try:
            wheel_msg = TbWheelmessage.objects.filter(id=data['id'])
            wheel_msg.update(w_no=data["w_no"],
                             w_type=data["w_type"],
                             w_feed=data["w_feed"],
                             w_speed=data["w_speed"],
                             w_gran=data["w_gran"],
                             m_type=data["m_type"],
                             w_station=data["w_station"],
                             desi_id=str(request.user),
                             last_name=str(request.user.last_name),
                             desi_time=now)
            content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST","PUT","DELETE"])
def cutter_type(request):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        result = TbCTypeHead.objects.values()
        if result:
            for i in result:
                i["t_type"] = i["c_type"]
                del i["c_type"]
                content["payload"].append(i)
        return Response(content)

    if request.method == "POST":
        content ={"payload" :[], "status":0,"errmsg" :''}
        c_type = request.data["c_type"]

        try:
            c_type_msg=TbCTypeHead.objects.filter(c_type=c_type).values()
            if c_type_msg:
                raise Exception("此刀具類型已经存在，無法保存")
            else:
                tb_type_head=TbCTypeHead()
                tb_type_head.c_type=c_type
                tb_type_head.save()

                #id=tb_type_head.id
            content["payload"].append(tb_type_head.id)

        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    if request.method =="PUT":
        content = {"payload": [], "status": 0, "errmsg": ''}
        c_type_id = request.data["c_type_id"]
        c_type = request.data["c_type"]

        try:
            tb_type_body=TbCTypeBody.objects.filter(c_type=c_type_id).values()
            c_type_msg = TbCTypeHead.objects.filter(c_type=c_type).values()

            if tb_type_body or c_type_msg:
                raise Exception("此刀具類型已有尺寸代碼或者此刀具類型已经存在，無法修改")

            else:
                tb_type_head=TbCTypeHead.objects.filter(id=c_type_id)

                tb_type_head.update(c_type=c_type)

                content['payload'].append("OK")

        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


    if request.method =="DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}
        id = request.GET.get("id", None)
        #c_type = request.data["c_type"]

        if not id:
            raise Exception("請傳入刀具類型id")

        try:
            tb_type_body=TbCTypeBody.objects.filter(c_type=id).values()
            # c_type_msg = TbCTypeHead.objects.filter(c_type=c_type).values()

            if tb_type_body :
                raise Exception("此刀具類型已有尺寸代碼，無法刪除")

            else:
                TbCTypeHead.objects.filter(id=id).delete()
                content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT"])
def desi_size(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            t_type = TbDesignmessage.objects.filter(id=pk).values('t_type')
            if t_type:
                cutter_id = TbCTypeHead.objects.filter(c_type=t_type[0]['t_type']).values('id')
                if cutter_id:
                    result = TbCTypeBody.objects.filter(c_type_id=cutter_id[0]['id']).order_by("desc1").values()
                    for i in result:
                        content["payload"].append(i)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    if request.method == "POST":
        #print(1111)

        content = {"payload": [], "status": 0, "errmsg": ''}
        try:

            user = request.user
            now = datetime.datetime.now()
            data = request.data["data"]
            result = json.loads(data)
            many = []
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver','t_type')
            t_head = TbCTypeHead.objects.filter(c_type=t_msg[0]["t_type"]).values()
            for i in result:
                if not i["id"]:
                    #print(2222)
                    #code = TbCTypeBody.objects.filter(size_name=i["grindingsite"],c_type=t_head[0]['id']).values()
                    code = TbCTypeBody.objects.filter(size_code=i["d_code"],c_type=t_head[0]['id']).values()
                    #print(code[0]["size_code"],'+++',code[0]["size_name"])
                    many.append(TbDesignsize(t_name=t_msg[0]["t_name"],
                                             t_ver=t_msg[0]["t_ver"],
                                             d_code=code[0]['size_code'],
                                             grindingsite=code[0]["size_name"],
                                             g_type=i["g_type"],
                                             g_size=i["g_size"] if i["g_size"] else None,
                                             g_otol=i["g_otol"] if i["g_otol"] else None,
                                             g_itol=i["g_itol"] if i["g_itol"] else None,
                                             desi_id=user,
                                             last_name=request.user.last_name,
                                             desi_time=now, toolt_id=pk,desc1=code[0]['desc1']))


                else:
                    #print(5555555)

                    sizt_msg = TbDesignsize.objects.filter(id=i['id'])

                    for z in sizt_msg.values('g_type','g_size','g_otol','g_itol'):
                        # print(1,i["g_type"], 2,z['g_type'])
                        # print(1,i["g_size"],2,z['g_size'])
                        # print(1,i["g_otol"], 2,z['g_otol'])
                        # print(1,i["g_itol"], 2,z["g_itol"])

                        # if i["g_size"] and i["g_otol"] and i["g_itol"]:
                        #print(666666)

                        if z["g_type"] and (z["g_size"] or z["g_size"]==0.0) and (z["g_otol"] or z["g_otol"]==0.0) and (z["g_itol"] or z["g_itol"]==0.0) and i["g_size"] and i["g_otol"] and i["g_itol"]:
                            #print(777777)

                            if str(i["g_type"])!=str(z['g_type']) or float(i["g_size"])!=float(z['g_size']) or float(i["g_otol"])!=float(z['g_otol']) or float(i["g_itol"])!=float(z['g_itol']):
                                #print(11)
                                sizt_msg.filter(id=i['id']).update(g_type=i["g_type"] if i["g_type"] else None,
                                                                   g_size=i["g_size"] if i["g_size"] else None,
                                                                   g_otol=i["g_otol"] if i["g_otol"] else None,
                                                                   g_itol=i["g_itol"] if i["g_itol"] else None,
                                                                   desi_id=str(user),
                                                                   last_name=str(request.user.last_name),
                                                                   desi_time=now)
                            # elif i["g_type"] == None  or i["g_size"] == None or i["g_otol"] == None or i["g_itol"] == None:
                            #     print(12)
                            #     pass
                            else:
                                #print(13)
                                pass

                        else:
                            #print(888888)
                            if i['g_type']:
                                a=i['g_type']
                            else:
                                a='None'
                            if i['g_size']:
                                b=i['g_size']
                            else:
                                b='None'
                            if i['g_otol']:
                                c=i['g_otol']
                            else:
                                c='None'
                            if i['g_itol']:
                                d=i['g_itol']
                            else:
                                d='None'

                            #print(77,str(i["g_type"]), 1,a,2,b,3,c,4,d)
                            if str(z["g_type"]) != str(a) or str(z["g_size"]) != str(
                                b) or str(z["g_otol"]) != str(c) or str(z["g_itol"]) != str(
                                d):
                                #print(15)
                                sizt_msg.filter(id=i['id']).update(g_type=i["g_type"] if i["g_type"] else None,
                                                                   g_size=i["g_size"] if i["g_size"] else None,
                                                                   g_otol=i["g_otol"] if i["g_otol"] else None,
                                                                   g_itol=i["g_itol"] if i["g_itol"] else None,
                                                                   desi_id=str(user),
                                                                   last_name=str(request.user.last_name),
                                                                   desi_time=now)
                            else:
                                #print(14)
                                pass

            TbDesignsize.objects.bulk_create(many)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def biotech(request, pk):
    if request.method == "GET":
        # user = request.user
        # last_name = request.user.last_name
        #site=request.user.site
        #print('111',user,username,site)
        content = {"payload": {'data': [], 'design_msg': '', 'm_type': []}, "status": 0, "errmsg": ''}
        try:
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')
            wheel_log = TbWheelSort.objects.filter(toolt=pk).exclude(m_stat='完工').values()
            m_type = TbWheelmessage.objects.filter(toolt=pk).values('m_type').distinct()
            if wheel_log:
                for i in wheel_log:
                    i["update_time"] = i["update_time"].strftime("%Y-%m-%d %H:%M:%S")
                    content["payload"]['data'].append(i)
            if m_type:
                for j in m_type:
                    content["payload"]['m_type'].append(j['m_type'])
            if t_msg:
                content["payload"]['design_msg'] = {'t_name': t_msg[0]['t_name'], 't_ver': t_msg[0]['t_ver']}
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "POST":
        #print(111)
        content = {"payload": [], "status": 0, "errmsg": ''}
        user = request.user
        try:
            #print(222)

            #print(1111)
            now = datetime.datetime.now()
            data = request.data["data"]
            data = json.loads(data)



            if data[0]['m_no'].split('-')[1] in ['RX7','MX7','TX7']:
                file_list = ['txt', 'scr']

            elif data[0]['m_no'].split('-')[1] in ['620','628','629','NANO']:
                file_list = ['vgp', 'vg', 'rvg']

            else:
                file_list = ['txt', 'pdf', 'xlsx', 'scr', 'xls', 'vgp', 'vg', 'rvg']

            my_uuid = uuid.uuid4()
            f_name = request.FILES.get('file_name')
            #print(f_name)
            if f_name:
                #print(3333)

                spfile = str(f_name).split('.')

                #spfile = ''
                if spfile[-1] in file_list:

                # for i in file_list:
                #     spfile = str(f_name).split(i)[:1]
                # # print('spfile', spfile)
                # # spfile = str(f_name).split('.')

                    new_name = str(my_uuid) + '_' + str(f_name)
                    #print(new_name)

                    file_origin_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)  # 文件路径
                    file_path = os.path.join(settings.DRAWING_PATH, new_name)  # 数据库存放文件路径

                    file_origin_name = file_origin_path + new_name
                    # print(2222)
                    with open(file_origin_name, 'wb') as flhd:  # 写入
                        flhd.write(f_name.read())
                        flhd.close()
                else:
                    raise Exception("文件格式有誤:RX7,MX7,TX7机台只能上传'scr'、'txt'格式文件; 620，628，629，NANO机台只能上传'vgp'、'vg'、'rvg'格式文件",str(f_name))
            else:
                # my_uuid=None
                file_path=None


            wheel_sort_mk=TbWheelSort.objects.filter(toolt=pk,m_no=data[0]['m_no']).values().order_by('mark_num').last()
            if wheel_sort_mk:
                #print(5555)
                if wheel_sort_mk['mark_num']:
                    mark_num = int(wheel_sort_mk['mark_num']) + 1

                else:
                    mark_num = 1

            else:
                mark_num=1

            #print(mark_num)
            many = []
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')
            if data and t_msg:
                for i in data:
                    #print(666)   raise Exception("此刀具已有補正記錄，無法刪除")
                    #if i["w_name"] and (float(i["w_diam"]) or float(i["w_diam"])==0.0) and (float(i["w_arc"]) or float(i["w_arc"])==0.0) and (float(i["w_rnot1"]) or float(i["w_rnot1"])==0.0):
                    # and (i["w_diam"] or float(i["w_diam"])==0.0) and (i["w_arc"] or float(i["w_arc"])==0.0) and (i["w_rnot1"] or float(i["w_rnot1"])==0.0)
                    if i["w_name"]:

                        pattern = re.compile(r'^[+-]?\d+(?:\.\d{1,4})?$')
                        result1 = pattern.match(i["w_diam"])
                        result2 = pattern.match(i["w_arc"])
                        result3 = pattern.match(i["w_rnot1"])
                        if result1:
                            pass
                        else:
                            raise Exception("砂輪直徑請輸入數字")

                        if result2:
                            pass
                        else:
                            raise Exception("砂輪R角請輸入數字")

                        if result3:
                            pass
                        else:
                            raise Exception("径向跳動請輸入數字")

                        many.append(TbWheelSort(t_name=t_msg[0]["t_name"],
                                                t_ver=t_msg[0]["t_ver"],
                                                m_no=i["m_no"],
                                                w_no=i["w_no"],
                                                w_name=i["w_name"],
                                                w_ceme=i["w_ceme"],
                                                w_bran=i["w_bran"],
                                                w_diam=i["w_diam"],
                                                w_gran=i["w_gran"],
                                                w_arc=i["w_arc"],
                                                w_rnot1=i["w_rnot1"],
                                                m_stat="待上機",
                                                engi_id=user,
                                                last_name=request.user.last_name,
                                                status=2,
                                                update_time=now,
                                                toolt_id=pk,
                                                mark_num=mark_num,
                                                uuid=my_uuid if my_uuid else None,
                                                file_path0=file_path if file_path else None,
                                                end_time=None,
                                                w_station=i["w_station"] if i["w_station"] else None))


                    else:
                        raise Exception("砂輪編號,砂輪直徑,砂輪R角,径向跳動不能為空")

                TbWheelSort.objects.bulk_create(many)
            content["payload"] = "OK"
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "PUT":
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        try:
            #file_list = ['txt', 'pdf', 'xlsx', 'scr', 'xls', 'vgp','vg','rvg']


            if data['m_no'].split('-')[1] in ['RX7','MX7','TX7']:
                file_list = ['txt', 'scr']

            elif data['m_no'].split('-')[1] in ['620','628','629','NANO']:
                file_list = ['vgp', 'vg', 'rvg']

            else:
                file_list = ['txt', 'pdf', 'xlsx', 'scr', 'xls', 'vgp', 'vg', 'rvg']


            f_name = request.FILES.get('file_name')
            my_uuid = uuid.uuid4()
            if f_name:
                # spfile = ''
                # for i in file_list:
                #     spfile = str(f_name).split(i)[:1]
                # print('spfile', spfile)
                # spfile = str(f_name).split('.')
                spfile = str(f_name).split('.')

                #spfile = ''
                if spfile[-1] in file_list:

                    new_name = str(my_uuid) + '_' + str(f_name)

                    # print(new_name)

                    file_origin_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)  # 文件路径
                    file_path = os.path.join(settings.DRAWING_PATH, new_name)  # 数据库存放文件路径

                    file_origin_name = file_origin_path + new_name
                    # print(2222)
                    with open(file_origin_name, 'wb') as flhd:  # 写入
                        flhd.write(f_name.read())
                        flhd.close()

                    wheel_sort_link=TbWheelSort.objects.filter(id=data["id"]).values().last()
                    #print(wheel_sort_link['mark_num'])

                    TbWheelSort.objects.filter(toolt=pk,m_no=data['m_no'],mark_num=wheel_sort_link['mark_num']).update(
                        uuid = my_uuid if my_uuid else None,
                        file_path0 = file_path if file_path else None)
                else:
                    raise Exception("文件格式有誤:RX7,MX7,TX7机台只能上传'scr'、'txt'格式文件; 620，628，629，NANO机台只能上传'vgp'、'vg'、'rvg'格式文件", str(f_name))
            else:
                pass

            now = datetime.datetime.now()
            pattern = re.compile(r'^[+-]?\d+(?:\.\d{1,4})?$')
            result1 = pattern.match(data["w_diam"])
            result2 = pattern.match(data["w_arc"])
            result3 = pattern.match(data["w_rnot1"])
            if result1:
                pass
            else:
                raise Exception("砂輪直徑請輸入數字")

            if result2:
                pass
            else:
                raise Exception("砂輪R角請輸入數字")

            if result3:
                pass
            else:
                raise Exception("径向跳動請輸入數字")
            TbWheelSort.objects.filter(id=data["id"]).update(
                w_ceme=data["w_ceme"],
                w_bran=data["w_bran"],
                w_diam=data["w_diam"],
                w_gran=data["w_gran"],
                w_arc=data["w_arc"],
                w_rnot1=data["w_rnot1"],
                #w_station=data["w_station"],
                update_time=now,
                status=2
            )
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            # data = request.data
            id = request.GET.get("id", None)
            if not id:
                raise Exception("請傳入砂輪修整id！")
            TbWheelSort.objects.filter(id=id).delete()
            content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST","PUT"])
def productor(request, pk):
    if request.method == "GET":
        content = {"payload": {'data': [], 'page': []}, "status": 0, "errmsg": ''}
        try:
            m_no = request.GET.get("m_no", None)
            status = request.GET.get("status", '4')

            id = request.GET.get("id", '')
            # if not m_no:raise Exception(u"你未在此機台進行砂輪修整")
            if not id:
                result = TbProductHead.objects.filter(toolt=pk, m_no=m_no, status=status).filter(Q(m_stat='在制') | Q(m_stat='挂起')).values()
            else:
                result = TbProductHead.objects.filter(toolt=pk, m_no=m_no, status=status).filter(Q(m_stat='在制') | Q(m_stat='挂起')).values()
            if result:
                for i in result:
                    i["op_time"] = i["op_time"].strftime("%Y-%m-%d %H:%M:%S")


            if int(status)!=4:
                page_num = request.GET.get("page", '')

                if page_num:
                    pag_class = Paginator(result, 20)
                else:
                    pag_class = Paginator(result, len(result) + 1)
                    page_num = 1
                select_data = pag_class.page(page_num)
                for i in select_data:
                    content["payload"]['data'].append(i)
                content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                              'page_number': pag_class.page_range[-1]}

            else:
                for j in result:
                    content["payload"]['data'].append(j)
                content["payload"]["page"] = {'count': None, 'page': None,
                                              'page_number': None}


        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "POST":
        pass
    elif request.method == "PUT":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            # m_no = request.GET.get('m_no', None)
            # action = request.GET.get('action', '')
            m_no= request.data["m_no"]
            action = request.data["action"]
            now = datetime.datetime.now()
            if action != "rework":
                TbProductHead.objects.filter(toolt=pk, m_no=m_no).update(m_stat='挂起',end_time=now)

                TbAblation.objects.filter(toolt=pk, m_no=m_no).update(m_stat='挂起',end_time=now)

                TbWheelSort.objects.filter(toolt=pk, m_no=m_no).update(m_stat='挂起',end_time=now)

                head_id = TbProductHead.objects.filter(toolt=pk, m_no=m_no).values('id', 'm_no')
                if head_id:
                    for i in head_id:
                        TbProductionmessage.objects.filter(head_id=i['id'], m_no=i['m_no']).update(m_stat='挂起',end_time=now)
            else:
                TbProductHead.objects.filter(toolt=pk, m_no=m_no).update(m_stat='在制', end_time=now)

                TbAblation.objects.filter(toolt=pk, m_no=m_no).update(m_stat='在制', end_time=now)

                TbWheelSort.objects.filter(toolt=pk, m_no=m_no).update(m_stat='在制', end_time=now)

                head_id = TbProductHead.objects.filter(toolt=pk, m_no=m_no).values('id', 'm_no')
                if head_id:
                    for i in head_id:
                        TbProductionmessage.objects.filter(head_id=i['id'], m_no=i['m_no']).update(m_stat='在制',
                                                                                                   end_time=now)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 1
        return Response(content)




@api_view(http_method_names=["GET", "POST", "PUT"])
def productor_addit(request, pk):
    if request.method == "GET":
        try:
            #now = datetime.datetime.now()
            content = {"payload": {'data': [], 'wheel': [], 'design_msg': ''}, "status": 0, "errmsg": ''}
            m_no = request.GET.get("m_no", None)
            id = request.GET.get("id", "")
            status=request.GET.get("status", "")
            if not status and not id: raise Exception(u"你未输入status 或 id！")


            #排序统一
            result = TbDesignmessage.objects.filter(id=pk).values()[0]

            type_head_msg = TbCTypeHead.objects.filter(c_type=result["t_type"]).values()

            if type_head_msg:
                for k in type_head_msg:
                    type_body_msg = TbCTypeBody.objects.filter(c_type=k['id']).values('size_code', 'desc1')
                    if type_body_msg:
                        for z in type_body_msg:
                            TbDesignsize.objects.filter(d_code=z['size_code'],toolt=pk).update(desc1=z['desc1'])


            if id and m_no:
                #p_msg = TbProductionmessage.objects.filter(head=id).values()
                t_msg = TbProductHead.objects.filter(id=id).values()
                w_wheel = TbWheelSort.objects.filter(m_no=t_msg[0]['m_no'], toolt=pk, status=2).values(
                    'w_no').distinct()


                t_size = TbDesignsize.objects.filter(toolt=pk).values('t_name', 'd_code',
                                                                       'g_type', 'g_size',
                                                                        'g_otol',
                                                                        'g_itol', 't_ver',
                                                                        'grindingsite').order_by('desc1')


                for t in t_msg:
                    content["payload"]['design_msg'] = t
                for j in w_wheel:
                    content["payload"]['wheel'].append(j)

                # if p_msg:
                #     for i in p_msg:
                #         t_size = TbDesignsize.objects.filter(toolt=pk, d_code=i['d_code']).values('t_name', 'd_code',
                #                                                                                   'g_type', 'g_size',
                #                                                                                   'g_otol',
                #                                                                                   'g_itol', 't_ver',
                #                                                                                   'grindingsite', )
                #         if t_size:
                #             i['grindingsite'] = t_size[0]['grindingsite']
                #             if t_size[0]['g_size']:
                #                 if t_size[0]['g_itol']:
                #                     g_itol = t_size[0]['g_size'] + t_size[0]['g_itol']
                #                 else:
                #                     g_itol = t_size[0]['g_size']
                #                 if t_size[0]['g_otol']:
                #                     g_otol = t_size[0]['g_size'] + t_size[0]['g_otol']
                #                 else:
                #                     g_otol = t_size[0]['g_size']
                #                 i['scope'] = str(round(g_itol, 3)) + '-' + str(round(g_otol, 3))
                #             else:
                #                 i['scope'] = 'NA'
                #             content['payload']['data'].append(i)


                if t_size:
                    #print(t_size)
                    #print(len(t_size))
                    for i in t_size:
                        #print(1111)
                        if i['g_size'] or i['g_size']==0 or i['d_code'] in ['m1','m2','m3','m4','z1','z2']:

                            dict2={'id':'','me_num':'','wheel_1':'','wheel_2':'','wheel_3':'','p_para':'','scope':''}

                            p_msg1=TbProductionmessage.objects.filter(head=id,d_code=i['d_code']).values('id','me_num','wheel_1','wheel_2',
                                                                                                         'wheel_3','p_para')

                            # print(i['me_num'])
                            #print(99)
                            #print(p_msg1[0]['me_num'])
                            #print(222222)
                            dictMerged2 = dict(i, **dict2)

                            if p_msg1:
                                dictMerged2['id'] = p_msg1[0]['id']
                                dictMerged2['me_num']=p_msg1[0]['me_num']
                                dictMerged2['wheel_1'] = p_msg1[0]['wheel_1']
                                dictMerged2['wheel_2'] = p_msg1[0]['wheel_2']
                                dictMerged2['wheel_3'] = p_msg1[0]['wheel_3']
                                dictMerged2['p_para'] = p_msg1[0]['p_para']
                                # dictMerged2['mark_num'] = p_msg1[0]['mark_num']
                                # dictMerged2['uuid'] = p_msg1[0]['uuid']
                                # dictMerged2['file_path'] = p_msg1[0]['file_path']
                            else:
                                pass

                            if dictMerged2['g_size'] or dictMerged2['g_size']==0:
                                if dictMerged2['g_itol']:
                                    g_itol=dictMerged2['g_size']+dictMerged2['g_itol']
                                else:
                                    g_itol = dictMerged2['g_size']
                                if dictMerged2['g_otol']:
                                    g_otol=dictMerged2['g_size']+dictMerged2['g_otol']
                                else:
                                    g_otol=dictMerged2['g_size']

                                dictMerged2['scope'] = str(round(g_itol, 3)) + '-' + str(round(g_otol, 3))

                            else:
                                dictMerged2['scope'] = 'NA'

                            content['payload']['data'].append(dictMerged2)


            if m_no and not id:
                w_wheel = TbWheelSort.objects.filter(m_no=m_no, toolt=pk,
                                                     status=2).values('w_no').distinct()
                t_size = TbDesignsize.objects.filter(toolt=pk).values('t_name', 'd_code', 'g_type', 'g_size', 'g_otol',
                                                                      'g_itol', 't_ver', 'grindingsite', ).order_by('desc1')

                t_msg1 = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')
                t_msg = TbProductHead.objects.filter(status=status,toolt_id=pk,m_no=m_no).values('t_name','t_ver','m_no','ct','t_rnot','t_bmta','status').order_by('id')
                if t_msg:
                    for t in t_msg:
                        content["payload"]['design_msg'] = t
                else:
                    for t1 in t_msg1:
                        content["payload"]['design_msg'] = t1
                for j in w_wheel:
                    content["payload"]['wheel'].append(j)
                for i in t_size:
                    if i['g_size'] or i['g_size']==0:
                        if i['g_itol']:
                            g_itol = i['g_size'] + i['g_itol']
                        else:
                            g_itol = i['g_size']
                        if i['g_otol']:
                            g_otol = i['g_size'] + i['g_otol']
                        else:
                            g_otol = i['g_size']
                        i['scope'] = str(round(g_itol, 3)) + '-' + str(round(g_otol, 3))
                    else:
                        i['scope'] = 'NA'
                    if i['scope'] != 'NA' or i['d_code'] in ['m1','m2','m3','m4','z1','z2']:
                        content['payload']['data'].append(i)

            content['errmsg'] = 0
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    # if request.method == "PUT":
    #     try:
    #         now = datetime.datetime.now()
    #         content = {"payload": {'data': [], 'wheel': []}, "status": 0, "errmsg": ''}
    #         data = request.data
    #         tuer, null, false = 'tuer', 'null', 'false'
    #         measure = eval(data["measure"])
    #         data1 = eval(data["data"])
    #         status = eval(data["status"])
    #         user = request.user
    #         many = []
    #         t_msg = TbDesignmessage.objects.filter(id=pk).values()
    #         p_heda = TbProductHead()
    #         p_heda.ct = int(measure['ct'])
    #         p_heda.me_no = int(measure['me_no'])
    #         p_heda.t_name = t_msg[0]["t_name"]
    #         p_heda.t_ver = t_msg[0]["t_ver"]
    #         p_heda.t_no = measure['t_no']
    #         p_heda.m_no = measure['m_no']
    #         p_heda.t_bmta = measure['t_bmta']
    #         p_heda.t_rnot = measure['t_rnot']
    #         p_heda.status = status
    #         p_heda.op_id = user
    #         p_heda.op_time = now
    #         p_heda.toolt_id = pk
    #         p_heda.save()
    #         for i in data1:
    #             if not i["id"]:
    #                 #code = TbCTypeBody.objects.filter(size_name=i["grindingsite"]).values()
    #                 many.append(TbProductionmessage(t_name=t_msg[0]["t_name"],
    #                                                 t_ver=t_msg[0]["t_ver"],
    #                                                 d_code=i['d_code'],
    #                                                 p_para=i['p_para'],
    #                                                 wheel_1=i['wheel_1'],
    #                                                 wheel_2=i['wheel_2'],
    #                                                 wheel_3=i['wheel_3'],
    #                                                 me_num=float(i['me_num']) if i['me_num'] else None,
    #                                                 me_no=int(measure['me_no']),
    #                                                 t_no=measure['t_no'],
    #                                                 m_no=measure['m_no'],
    #                                                 t_bmta=measure['t_bmta'],
    #                                                 t_rnot=float(measure['t_rnot']),
    #                                                 status=status,
    #                                                 op_id=user,
    #                                                 m_stat="在制",
    #                                                 op_time=now, head_id=p_heda.id))
    #             else:
    #                 sizt_msg = TbProductionmessage.objects.filter(id=i['id'])
    #                 sizt_msg.update(p_para=i['p_para'], wheel_1=i['wheel_1'], wheel_2=i['wheel_2'],
    #                                 wheel_3=i['wheel_3'], me_num=float(i['me_num']) if i['me_num'] else None,
    #                                 me_no=int(measure['me_no']), t_no=measure['t_no'],
    #                                 m_no=measure['m_no'], t_bmta=measure['t_bmta'], t_rnot=float(measure['t_rnot']),
    #                                 op_time=now, )
    #         TbProductionmessage.objects.bulk_create(many)
    #         # measure = data['measure']
    #         content['errmsg'] = 0
    #     except Exception as e:
    #         content["status"] = 1
    #         content["errmsg"] = str(e)
    #     finally:
    #         return Response(content)

    if request.method == "POST":
        try:
            #print(request.data['data'])
            now = datetime.datetime.now()
            content = {"payload": {'data': [], 'wheel': []}, "status": 0, "errmsg": ''}
            user = request.user
            # last_name=request.user.last_name
            ct = int(request.data['ct'])
            me_no = int(request.data['me_no'])
            id = request.data['id']
            t_no = request.data['t_no']
            m_no = request.data['m_no']
            t_bmta = request.data['t_bmta']
            t_rnot = request.data['t_rnot']
            status = request.data['status']
            #print(status)
            data = json.loads(request.data['data'])
            #print('000',data)

            many = []


            if int(status)==4:
                #print(444444)
                #file_list = ['txt', 'pdf', 'xlsx', 'scr', 'xls', 'vgp','vg','rvg']

                if m_no.split('-')[1] in ['RX7', 'MX7', 'TX7']:
                    file_list = ['txt', 'scr']

                elif m_no.split('-')[1] in ['620', '628', '629', 'NANO']:
                    file_list = ['vgp', 'vg', 'rvg']

                else:
                    file_list = ['txt', 'pdf', 'xlsx', 'scr', 'xls', 'vgp', 'vg', 'rvg']

                f_name = request.FILES.get('file_name')

                t_msg = TbDesignmessage.objects.filter(id=pk).values()

                my_uuid = uuid.uuid4()

                t_ws_uuid = TbWheelSort.objects.filter(toolt=pk, m_no=m_no).values('uuid').last()
                t_ws_uuid = t_ws_uuid['uuid']

                # print(type(f_name))
                #print(1111)
                if f_name:
                    # spfile = ''
                    # for i in file_list:
                    #     spfile = str(f_name).split(i)[:1]
                    # print('spfile', spfile)
                    # spfile = str(f_name).split('.')

                    spfile = str(f_name).split('.')

                    # spfile = ''
                    if spfile[-1] in file_list:
                        new_name = str(my_uuid) + '_' + str(f_name)
                        # print(new_name)

                        file_origin_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)  # 文件路径
                        file_path = os.path.join(settings.DRAWING_PATH, new_name)  # 数据库存放文件路径

                        file_origin_name = file_origin_path + new_name
                        # print(2222)
                        with open(file_origin_name, 'wb') as flhd:  # 写入
                            flhd.write(f_name.read())
                            flhd.close()
                    else:
                        raise Exception("文件格式有誤:文件格式有誤:RX7,MX7,TX7机台只能上传'scr'、'txt'格式文件; 620，628，629，NANO机台只能上传'vgp'、'vg'、'rvg'格式文件", str(f_name))
                else:
                    file_path=None

                if id:
                    #print(444.1111)
                    p_heda = TbProductHead.objects.filter(id=id)

                    if f_name:
                        file_path1=file_path
                    else:
                        if p_heda.values('file_path').last():
                            file_path1=p_heda.values('file_path').last()
                            file_path1=file_path1['file_path']
                        else:
                            file_path1=None

                    p_heda.update(ct=int(ct), me_no=int(me_no), t_no=t_no,
                                  t_bmta=t_bmta,
                                  t_rnot=t_rnot, op_id=str(user),
                                  last_name=str(request.user.last_name),
                                  #op_time=now,
                                  uuid=t_ws_uuid,file_path=file_path1)

                    t_pro_num = TbProductionmessage.objects.filter(head=id, m_no=m_no).values(
                        'mark_num').last()
                    #print(t_pro_num)
                    if t_pro_num:
                        if t_pro_num['mark_num']:

                            mark_num = int(t_pro_num['mark_num']) + 1
                        else:

                            mark_num = 1
                    else:
                        mark_num = 1

                else:
                    #print(444.2222)
                    tb_head=TbProductHead.objects.filter(uuid=t_ws_uuid,t_no=t_no,status=status).values()
                    if tb_head:
                        raise Exception("该調機料號已經存在！")
                    else:
                        p_heda = TbProductHead()
                        p_heda.ct = int(ct)
                        p_heda.me_no = int(me_no)
                        p_heda.t_name = t_msg[0]["t_name"]
                        p_heda.t_ver = t_msg[0]["t_ver"]
                        p_heda.t_no = t_no
                        p_heda.m_no = m_no
                        p_heda.t_bmta = t_bmta
                        p_heda.t_rnot = t_rnot
                        p_heda.status = status
                        p_heda.op_id = user
                        p_heda.last_name=request.user.last_name
                        p_heda.op_time = now
                        p_heda.toolt_id = pk
                        p_heda.m_stat='在制'
                        p_heda.uuid=t_ws_uuid
                        p_heda.file_path=file_path
                        p_heda.end_time=None
                        p_heda.save()
                        id=p_heda.id
                        mark_num = 1
                #print(444.6666)
            else:
                #print(55555.5555)
                mark_num=None
                #t_ws_uuid=None
                file_path=None

                t_msg = TbDesignmessage.objects.filter(id=pk).values()

                t_ws_uuid = TbProductionmessage.objects.filter(t_name=t_msg[0]['t_name'],t_ver=t_msg[0]["t_ver"],m_no=m_no,status=4).values('uuid').last()
                t_ws_uuid = t_ws_uuid['uuid']

                if id:
                    p_heda = TbProductHead.objects.filter(id=id)
                    p_heda.update(ct=int(ct), me_no=int(me_no), t_no=t_no,
                                  t_bmta=t_bmta,
                                  t_rnot=t_rnot, op_id=str(user),
                                  last_name=str(request.user.last_name),
                                  #op_time=now,
                                  uuid=t_ws_uuid)

                else:
                    #print(5555.666)
                    tb_head = TbProductHead.objects.filter(uuid=t_ws_uuid, t_no=t_no, status=status).values()
                    if tb_head:
                        raise Exception("该刀具流水號已經存在！")
                    else:

                        p_heda = TbProductHead()
                        p_heda.ct = int(ct)
                        p_heda.me_no = int(me_no)
                        p_heda.t_name = t_msg[0]["t_name"]
                        p_heda.t_ver = t_msg[0]["t_ver"]
                        p_heda.t_no = t_no
                        p_heda.m_no = m_no
                        p_heda.t_bmta = t_bmta
                        p_heda.t_rnot = t_rnot
                        p_heda.status = status
                        p_heda.op_id = user
                        p_heda.last_name=request.user.last_name
                        p_heda.op_time = now
                        p_heda.toolt_id = pk
                        p_heda.m_stat='在制'
                        p_heda.uuid=t_ws_uuid
                        p_heda.file_path = file_path
                        p_heda.end_time=None
                        p_heda.save()

                        id = p_heda.id
                        #print(p_heda.last_name)

            for i in data:
                #print(66666)
                if int(status) == 4:
                    dict2 = {'wheel_1': '', 'wheel_2': '', 'wheel_3': '', 'p_para': ''}
                    i=dict(i,**dict2)
                    ap_num=None
                else:
                    a_num = TbAblation.objects.filter(toolt=pk, m_no=m_no).values('ap_num').last()
                    if a_num:
                        if a_num['ap_num']:
                            ap_num = a_num['ap_num']

                        else:
                            ap_num = None
                    else:
                        ap_num = None

                # code = TbCTypeBody.objects.filter(size_name=i["grindingsite"]).values()
                if not i['id']:
                    #print(77777)
                    # if id:
                    #     head_id =data1['id']
                    # else:
                    #     head_id = p_heda.id
                    if i['me_num']:
                        many.append(TbProductionmessage(t_name=t_msg[0]["t_name"],
                                                        t_ver=t_msg[0]["t_ver"],
                                                        d_code=i['d_code'],
                                                        p_para=i['p_para'],
                                                        wheel_1=i['wheel_1'],
                                                        wheel_2=i['wheel_2'],
                                                        wheel_3=i['wheel_3'],
                                                        me_num=float(i['me_num']) if i['me_num'] else None,
                                                        me_no=int(me_no),
                                                        t_no=t_no,
                                                        m_no=m_no,
                                                        t_bmta=t_bmta,
                                                        t_rnot=float(t_rnot),
                                                        status=status,
                                                        op_id=user,
                                                        last_name=request.user.last_name,
                                                        m_stat="在制",
                                                        op_time=now,
                                                        head_id=id,
                                                        mark_num=mark_num,
                                                        uuid=t_ws_uuid,
                                                        end_time=None,
                                                        ap_num=ap_num))
                    else:
                        pass


                else:
                    #print(888888)
                    sizt_msg = TbProductionmessage.objects.filter(id=i['id'])
                    if i['me_num']:
                        sizt_msg.update(p_para=i['p_para'], wheel_1=i['wheel_1'], wheel_2=i['wheel_2'],
                                        wheel_3=i['wheel_3'], me_num=float(i['me_num']) if i['me_num'] else None,
                                        me_no=int(me_no), t_no=t_no,
                                        m_no=m_no, t_bmta=t_bmta, t_rnot=float(t_rnot),
                                        op_time=now)
                    else:
                        pass
            #print(9999)
            TbProductionmessage.objects.bulk_create(many)
            #print(1010101010)
            content['errmsg'] = 0
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST"])
def machine(request):
    if request.method == "GET":
        try:
            content = {"payload": '', "status": 0, "errmsg": ''}
            m_type = request.GET.get('type', '')
            site = str(request.user.site)
            site_map = {'LH': 'SZ', '晉城': 'JC', 'S': 'SZ', '深圳': 'SZ', 'J': 'JC'}
            machine = []
            if m_type:
                type_list = m_type.split("/")
                if len(type_list) > 1:
                    result = TbMachine.objects.all().filter(Q(m_type=type_list[0]) | Q(m_type=type_list[1]),
                                                            site=site_map[site])
                else:
                    result = TbMachine.objects.all().filter(site=site_map[site], m_type=type_list[0])
            else:
                result = TbMachine.objects.all().filter(site=site_map[site])
            for i in result:
                machine.append(i.site + '-' + i.m_type + '-' + ('00' + i.cell_num)[-3:])
            content["payload"] = machine
            content['errmsg'] = 0
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "POST":
        pass


@api_view(http_method_names=["GET", "POST", "PUT"])
def wheel_no(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            user = request.user
            machine_type = request.GET.get("machine_type", None)
            if not machine_type: raise Exception(u"請傳入機台型號")
            wheel_no = TbWheelmessage.objects.filter(toolt=pk, m_type__icontains=machine_type). \
                values('w_no', 'w_type', 'w_gran','w_station').order_by('w_no')
            if wheel_no:
                for i in wheel_no:
                    content["payload"].append(i)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def grind(request, pk):
    if request.method == "GET":
        content = {"payload": {'data': [], 'design_msg': '', 'm_no': []}, "status": 0, "errmsg": ''}
        try:
            grind_msg = TbAblation.objects.filter(toolt=pk,m_stat='在制').values()
            m_no = TbWheelSort.objects.filter(toolt=pk, status=2).exclude(m_stat='完工').values('m_no').distinct()
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')
            if grind_msg:
                for i in grind_msg:
                    i["update_time"] = i["update_time"].strftime("%Y-%m-%d %H:%M:%S")
                    wheel_msg = TbWheelSort.objects.filter(id=i['wsort_id']).exclude(m_stat='完工').values('w_no',
                                                                                    'w_ceme', 'w_diam', 'w_arc',
                                                                                    'w_gran')
                    #print(TbWheelSort.objects.filter(id=i['wsort_id'],m_stat='在制').values('w_no','w_ceme', 'w_diam', 'w_arc','w_gran').query)
                    if wheel_msg:
                        i['w_no'] = wheel_msg[0]['w_no']
                        i['w_ceme'] = wheel_msg[0]['w_ceme']
                        i['w_diam'] = wheel_msg[0]['w_diam']
                        i['w_arc'] = wheel_msg[0]['w_arc']
                        i['w_gran'] = wheel_msg[0]['w_gran']
                        content["payload"]['data'].append(i)
            if m_no:
                for j in m_no:
                    content["payload"]['m_no'].append(j['m_no'])
            if t_msg:
                content["payload"]['design_msg'] = {'t_name': t_msg[0]['t_name'], 't_ver': t_msg[0]['t_ver']}
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "POST":
        content = {"payload": [], "status": 0, "errmsg": ''}
        user = request.user
        try:
            data = request.data["data"]
            data = json.loads(data)
            many = []
            now = datetime.datetime.now()
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_name', 't_ver')

            for z in data:
                a_num = TbAblation.objects.filter(toolt=pk, m_no=z["m_no"],wsort=z['id']).values('ap_num').last()
                if a_num:
                    if a_num['ap_num']:
                        ap_num = int(a_num['ap_num']) + 1

                    else:
                        ap_num = 1

                else:
                    ap_num = 1

            if data and t_msg:
                for i in data:
                    b_flag = TbWheelSort.objects.filter(toolt=pk, status=2, m_no=i["m_no"]).values()
                    if b_flag:
                        msg = TbAblation()
                        msg.t_name = t_msg[0]["t_name"]  # 刀具名稱
                        msg.t_ver = t_msg[0]["t_ver"]  # 刀具班次
                        msg.m_no = i["m_no"]  # 機台編號
                        msg.w_bala = float(i["w_bala"]) # 动平衡
                        msg.w_speed = float(i["w_speed"])  # 砂輪轉速
                        msg.w_feed = float(i["w_feed"])  # 砂輪轉速
                        msg.toolt_id = pk
                        msg.wsort_id = i["id"]
                        msg.m_stat = "在制"
                        msg.engi_id = user
                        msg.last_name=request.user.last_name
                        msg.update_time = datetime.datetime.now()
                        msg.status = 3  # 狀態
                        msg.end_time=None
                        msg.ap_num=ap_num
                        msg.save()
                    else:
                        raise Exception(u"你未在此機台進行砂輪修整")
            content["payload"] = {"id": msg.id}
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "PUT":
        content = {"payload": [], "status": 0, "errmsg": ''}
        data = request.data
        now = datetime.datetime.now()
        try:
            TbAblation.objects.filter(id=data["id"]).update(
                w_bala=float(data["w_bala"]),
                w_speed=float(data["w_speed"]),
                w_feed=float(data["w_feed"]),
                update_time=now,
                status=3
            )
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            #data = request.data
            id =request.GET.get('id',None)
            if not id:
                raise Exception("請傳入砂輪調磨削id！")
            TbAblation.objects.filter(id=id).delete()
            content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT"])
def grind_wheel_no(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            m_no = request.GET.get("m_no", None)
            if not m_no: raise Exception(u"請傳入機台編號")
            wheel_no = TbWheelSort.objects.filter(toolt=pk, m_no=m_no).exclude(m_stat='完工').values('id','t_name','t_ver','m_no','w_no',
                                                                              'w_ceme','w_gran','w_diam','w_arc').distinct()
            #print(wheel_no)
            if wheel_no:
                for i in wheel_no:
                    #print(i['id'])

                    ablation_msg=TbAblation.objects.filter(toolt_id=pk,m_no=m_no,wsort=i['id']).values('w_bala','w_speed','w_feed').last()
                    #print(ablation_msg)
                    if ablation_msg:
                        #print(1111)
                        i.update(ablation_msg)
                        content["payload"].append(i)
                    else:
                        #print(2222)
                        wheel_mag=TbWheelmessage.objects.filter(toolt_id=pk,t_name=i['t_name'],t_ver=i['t_ver'],
                                                                w_no=i['w_no'],w_type=i['w_ceme']).values('w_speed','w_feed').last()
                        #print(i['id'],'----',wheel_mag)
                        bala={'w_bala':''}
                        nobala = {'w_bala': '','w_speed':'','w_feed':''}
                        if wheel_mag:
                            i.update(wheel_mag)
                            i.update(bala)
                            #i['w_feed']=i['w_feed']
                            #print(i['w_feed'])
                        else:
                            i.update(nobala)

                        content["payload"].append(i)

        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT"])
def program(request):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            m_no = request.GET.get("m_no", None)
            site_num = request.GET.get("sitenum", None)
            if not m_no: raise Exception(u"請傳入機台編號")
            m_type = m_no.split("-")[1]
            modele_code = TbMachineCode.objects.filter(m_type=m_type).values('m_code')
            if modele_code and not site_num:
                result = TbGrindngsite.objects.filter(modelcode=modele_code[0]['m_code']).values()
            if site_num:
                result = TbCorrections.objects.filter(modelcode=modele_code[0]['m_code'], sitenum=site_num).values()
            if result:
                for i in result:
                    content["payload"].append(i)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT"])
def grind_msg(request):
    if request.method == "GET":
        content = {"payload": {'data': [], 'page': []}, "status": 0, "errmsg": ''}
        page_num = request.GET.get("page", '')
        status = request.GET.get('status', '')
        search = request.GET.get('search', None)
        #print(datetime.datetime.now())
        #找出挂起状态的记录，之后判断挂起是否超过十分钟，超过十分钟则将挂起变成完工，没有则继续挂起

        now = datetime.datetime.now()
        update_time_data = TbAblation.objects.filter(status=3,m_stat='挂起').values('id','end_time')
        op_time_data = TbProductHead.objects.filter(m_stat='挂起').filter(Q(status=4) | Q(status=5)).values('id','end_time')
        op_time_message = TbProductionmessage.objects.filter(m_stat='挂起').filter(Q(status=4) | Q(status=5)).values('id','end_time')
        update_time_wheel_sort = TbWheelSort.objects.filter(m_stat='挂起').values('id','end_time')

        if update_time_data:
            for i in update_time_data:
                if i["end_time"]:
                    if now-datetime.timedelta(minutes=10)>i["end_time"]:
                        TbAblation.objects.filter(id=i['id']).update(m_stat='完工')

        if op_time_data:
            for i in op_time_data:
                if i["end_time"]:
                    if now-datetime.timedelta(minutes=10)>i["end_time"]:
                        TbProductHead.objects.filter(id=i['id']).update(m_stat='完工')

        if op_time_message:
            for i in op_time_message:
                if i["end_time"]:
                    if now-datetime.timedelta(minutes=10)>i["end_time"]:
                        TbProductionmessage.objects.filter(id=i['id']).update(m_stat='完工')

        if update_time_wheel_sort:
            for i in update_time_wheel_sort:
                if i["end_time"]:
                    if now - datetime.timedelta(minutes=10) > i["end_time"]:
                        TbWheelSort.objects.filter(id=i['id']).update(m_stat='完工')

        try:
            if status == '4':
                modele_code = TbAblation.objects.filter(status=3).filter(Q(m_stat='在制') | Q(m_stat='挂起')).values('m_no', 'toolt_id','m_stat').distinct()
            else:
                modele_code = TbProductHead.objects.filter(status=4).filter(Q(m_stat='在制') | Q(m_stat='挂起')).values('m_no', 'toolt_id','m_stat').distinct()
            result = []
            #print(len(modele_code))
            #print(datetime.datetime.now())
            for i in modele_code:
                t_msg = TbDesignmessage.objects.filter(id=i['toolt_id']).values()
                #print(t_msg[0])
                #t_msg1 = t_msg[0]
                #t_msg1['m_no']=i['m_no']
                for j in t_msg:
                    j['m_no'] = i['m_no']
                    j["m_stat"] = i["m_stat"]
                    result.append(j)
                #result.append(t_msg1)
            #print(22222222222222222222222222)
            #print(datetime.datetime.now())
            #print(result)
            if result:
                _result = []
                if search:
                    search = str.lower(search)
                    for i in result:
                        if search in str.lower(i['t_name']) \
                        or search in str.lower(i['t_type']) \
                        or search in str(i['last_name']) \
                        or search in str.lower(i['desi_id']) \
                        or search in str.lower(i['t_spec']) \
                        or search in str.lower(i['m_no']):
                            _result.append(i)
                    result = _result
                if page_num:
                    pag_class = Paginator(result, 20)
                else:
                    pag_class = Paginator(result, len(result) + 1)
                    page_num = 1
                select_data = pag_class.page(page_num)
                if select_data:
                    for i in select_data:
                        i["desi_time"] = i["desi_time"].strftime("%Y-%m-%d %H:%M:%S")
                        content["payload"]["data"].append(i)
                content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                              'page_number': pag_class.page_range[-1]}
            else:
                raise Exception(u"沒有可以上機的刀具")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def desi_size_up(request, pk):
    if request.method == "GET":
        content = {"payload": {'data': []}, "status": 0, "errmsg": ''}
        try:
            t_size = TbCTypeBody.objects.filter(c_type=pk).values().order_by('desc1')
            if t_size:
                for i in t_size:
                    if i['size_picture']:
                        url = os.path.join(settings.MEDIA_ROOT, i['size_picture'])
                        #url = r"D:\photos\files\ST\file_manager\drawing\898db3b9e3c44adc83ef3ef4cb0ff5c3.png"
                        #url='r'url
                        url = r'%s'%(url)
                        #print(url)
                        try:
                            f = open(url, 'rb')  # 二进制方式打开图文件
                            ls_f = base64.b64encode(f.read())  # 读取文件内容，转换为base64编码
                            #print(ls_f)
                            i['_size_picture']=ls_f
                            f.close()
                        except Exception as e:
                            pass
                    content['payload']['data'].append(i)
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    if request.method == "PUT":
        #print(222)
        content = {"payload": {'data': []}, "status": 0, "errmsg": ''}
        try:
            #print(333)
            data = json.loads(request.data['data'])
            #print('data:',data)
            for i in data:
                # file_origin_path = None
                #print('size_name:', i['size_name'])
                #print('size_picture:', i['size_picture'][0:100])
                file_path = ""
                file_p = ""
                picture = i['size_picture']
                if picture.find('base64,') >= 0 and picture.find('data:') >= 0:
                    # print("picture....")
                    data_base64 = str.split(picture, 'base64,')[1]
                    data_base64 = base64.b64decode(data_base64)
                    # relative_path = os.path.join("media", "passport", "images",
                    #                              datetime.date.today().strftime("%Y%m%d"))

                    relative_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)
                    #relative_path = os.path.join(settings.WIN_ROOT, settings.DRAWING_PATH)


                    absolute_path = os.path.join("", relative_path)
                    # print(222)
                    if not os.path.exists(absolute_path):
                        with _mutex:
                            if not os.path.exists(absolute_path):
                                os.makedirs(absolute_path)
                    file_name = "%s.%s" % (uuid.uuid4().hex, "png")
                    file_p = os.path.join(settings.DRAWING_PATH, file_name)  # 数据库存放文件路径
                    tmp = os.path.join(absolute_path, file_name)
                    with open(tmp, 'wb') as handler:
                        handler.write(data_base64)
                        media_path = os.path.join(relative_path, file_name).replace('\\', '/')
                        file_path = media_path.replace('media\\', '')
                        # print(file_path)

                # if i['id'] and i['size_picture'][0:10] :
                #     #print(444)
                #     #print(i['id'])
                #     new_name = str(i['size_name']) + str(uuid.uuid1()) + '.' + 'png'
                #
                #     file_origin_path = os.path.join(settings.WIN_ROOT, settings.DRAWING_PATH)  # 文件路径
                #     file_origin_path = file_origin_path + new_name
                #
                #     strs=i['size_picture']
                #     strs=strs.split('base64')[1]
                #
                #     #print(strs)
                #     img = base64.b64decode(strs)
                #     #print(1.5555555)
                #     file = open(file_origin_path, 'wb')
                #     file.write(img)
                #     file.close()
                #     #print(444555555)
                #
                if i['id']:
                    size_msg = TbCTypeBody.objects.filter(id=i['id'])
                    size_msg.update(size_name=i["size_name"],
                                g_type=i['g_type'], status=1 if i['status'] else 0, context=i['context'],
                                desc1=int(i['desc1']) if i['desc1'] else None)
                    if file_p:
                        size_msg.update(size_picture=file_p)


                # elif i['id'] and not i['size_picture'][0:10]:
                #     #print(8888888888888)
                #     # print(i['id'])
                #     # print(file_origin_path)
                #     sizt_msg = TbCTypeBody.objects.filter(id=i['id'])
                #     sizt_msg.update(size_name=i["size_name"],
                #                     g_type=i['g_type'], status=1 if i['status'] else 0, context=i['context'],
                #                     desc1=int(i['desc1']) if i['desc1'] else None,
                #                     size_picture= file_origin_path if file_origin_path else None)

                # elif not i['id'] and i['size_picture'][0:10]:
                #     #print(7777777777)
                #     new_name = str(i['size_name']) + str(uuid.uuid1()) + '.' + 'jpg'
                #     file_origin_path = os.path.join(settings.WIN_ROOT, settings.DRAWING_PATH)  # 文件路径
                #     file_origin_path = file_origin_path + new_name
                #
                #     strs = i['size_picture']
                #     strs = strs.split('base64,')[-1]
                #
                #     img = base64.b64decode(strs)
                #
                #     file = open(file_origin_path, 'wb')
                #     file.write(img)
                #     file.close()
                #
                #     t_msg = TbCTypeBody()
                #     t_msg.c_type_id = pk
                #     t_msg.type_part = i['type_part']
                #     t_msg.size_name = i['size_name']
                #     t_msg.size_code = i['size_code']
                #     t_msg.g_type = i['g_type'] if i['g_type'] else None
                #     t_msg.status = 1 if i['status'] else 0
                #     t_msg.context = i['context'] if i['context'] else None
                #     t_msg.desc1 = int(i['desc1']) if i['desc1'] else None
                #     t_msg.size_picture = file_origin_path if file_origin_path else None
                #     t_msg.save()


                else:
                    #print(999999999)
                    tb_type_code=TbCTypeBody.objects.filter(c_type=pk,size_code=i['size_code']).values()
                    if tb_type_code:
                        raise Exception(u"此款刀具類型的尺寸代碼已經存在")
                    else:
                        t_msg = TbCTypeBody()
                        t_msg.c_type_id = pk
                        t_msg.type_part = i['type_part']
                        t_msg.size_name = i['size_name']
                        t_msg.size_code = i['size_code']
                        t_msg.g_type = i['g_type'] if i['g_type'] else None
                        t_msg.status = 1 if i['status'] else 0
                        t_msg.context = i['context'] if i['context'] else None
                        t_msg.desc1 = int(i['desc1']) if i['desc1'] else None
                        t_msg.size_picture = file_p
                        t_msg.save()
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    if request.method == "POST":
        content = {"payload": {'data': []}, "status": 0, "errmsg": ''}
        try:
            data = json.loads(request.data['data'])


            for i in data:

                file_path = ""
                file_p = ""
                picture = i['size_picture']

                if picture.find('base64,') >= 0 and picture.find('data:') >= 0:

                    data_base64 = str.split(picture, 'base64,')[1]
                    data_base64 = base64.b64decode(data_base64)
                    # relative_path = os.path.join("media", "passport", "images",
                    #                              datetime.date.today().strftime("%Y%m%d"))

                    relative_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)

                    absolute_path = os.path.join("", relative_path)

                    if not os.path.exists(absolute_path):
                        with _mutex:
                            if not os.path.exists(absolute_path):
                                os.makedirs(absolute_path)
                    file_name = "%s.%s" % (uuid.uuid4().hex, "png")
                    file_p = os.path.join(settings.DRAWING_PATH, file_name)  # 数据库存放文件路径
                    tmp = os.path.join(absolute_path, file_name)
                    with open(tmp, 'wb') as handler:
                        handler.write(data_base64)
                        media_path = os.path.join(relative_path, file_name).replace('\\', '/')
                        file_path = media_path.replace('media\\', '')


                t_msg = TbCTypeBody()
                t_msg.c_type_id = pk
                t_msg.type_part = i['type_part']
                t_msg.size_name = i['size_name']
                t_msg.size_code = i['size_code']
                t_msg.g_type = i['g_type'] if i['g_type'] else None
                t_msg.status = 1 if i['status'] else 0
                t_msg.context = i['context'] if i['context'] else None
                t_msg.desc1 = int(i['desc1']) if i['desc1'] else None
                t_msg.size_picture = file_p
                t_msg.save()
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    if request.method == "DELETE":
        content = {"payload": {'data': []}, "status": 0, "errmsg": ''}
        try:
            #data = request.data
            # data = eval(data["data"])
            id = request.GET.get('id',None)
            if not id:
                raise Exception("請傳入刀具尺寸id！")
            TbCTypeBody.objects.filter(id=id).delete()
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def save_as(request, pk):
    if request.method == "POST":
        content = {"payload": "", "status": 0, "errmsg": ''}
        try:
            data = request.data
            user = request.user
            now = datetime.datetime.now()
            t_ver = set(TbDesignmessage.objects.filter(t_name=data["t_name"]).values_list("t_ver", flat=1))
            if data["t_ver"].strip() in t_ver:
                # content["status"] = 1
                raise Exception("刀具名稱和版次已存在！")
                # content["errmsg"] = "刀具名稱和版次已存在！"
                # return content
            t_msg = TbDesignmessage.objects.filter(id=pk).values('t_spec', 't_type', 't_diam', 't_flen', 't_fnum',
                                                                 't_mmat')
            t_add = TbDesignmessage()
            t_add.t_name = data['t_name']
            t_add.t_ver = data['t_ver']
            t_add.t_spec = t_msg[0]['t_spec']
            t_add.t_type = t_msg[0]['t_type']
            t_add.t_diam = t_msg[0]['t_diam']
            t_add.t_flen = t_msg[0]['t_flen']
            t_add.t_fnum = t_msg[0]['t_fnum']
            t_add.t_mmat = t_msg[0]['t_mmat']
            t_add.desi_id = user
            t_add.last_name=request.user.last_name
            t_add.desi_time = now
            t_add.save()
            many = []
            many1 = []
            wheel_msg = TbWheelmessage.objects.filter(toolt_id=pk).values()
            for j in wheel_msg:
                many1.append(TbWheelmessage(t_name=t_add.t_name,
                                            t_ver=t_add.t_ver,
                                            w_no=j['w_no'],
                                            w_type=j["w_type"],
                                            w_gran=j["w_gran"],
                                            w_speed=j["w_speed"],
                                            w_feed=j["w_feed"],
                                            m_type=j["m_type"],
                                            w_station=j["w_station"],
                                            desi_id=user,
                                            last_name=request.user.last_name,
                                            desi_time=now, toolt_id=t_add.id))
            TbWheelmessage.objects.bulk_create(many1)
            t_size = TbDesignsize.objects.filter(toolt_id=pk).values()
            for i in t_size:
                if i["g_size"] or i["g_size"]==0.0:
                    if i["g_size"]:
                        i["g_size"]=float(i["g_size"])
                    if i["g_size"]==0.0:
                        i["g_size"]=float(0.0)
                else:
                    i["g_size"]=None

                if i["g_otol"] or i["g_otol"]==0.0:
                    if i["g_otol"]:
                        i["g_otol"]=float(i["g_otol"])
                    if i["g_otol"]==0.0:
                        i["g_otol"]=float(0.0)
                else:
                    i["g_otol"]=None

                if i["g_itol"] or i["g_itol"]==0.0:
                    if i["g_itol"]:
                        i["g_itol"]=float(i["g_itol"])
                    if i["g_itol"]==0.0:
                        i["g_itol"]=float(0.0)
                else:
                    i["g_itol"]=None
                many.append(TbDesignsize(t_name=t_add.t_name,
                                         t_ver=t_add.t_ver,
                                         d_code=i['d_code'],
                                         grindingsite=i["grindingsite"],
                                         g_type=i["g_type"],
                                         g_size=i["g_size"],
                                         g_otol=i["g_otol"],
                                         g_itol=i["g_itol"],
                                         desi_id=user,
                                         last_name=request.user.last_name,
                                         desi_time=now, toolt_id=t_add.id))
            TbDesignsize.objects.bulk_create(many)
            content["payload"] = {"id": t_add.id}
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def related_tool(request):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            t_type = request.GET.get('t_type', None)
            t_diam = request.GET.get('t_diam', None)
            t_fnum = request.GET.get('t_fnum', None)
            t_mmat = request.GET.get('t_mmat', None)
            if not t_diam or not t_type or not t_fnum or not t_mmat:
                raise Exception("請填寫完整")
            t_msg = TbDesignmessage.objects.filter(t_type=t_type, t_diam=t_diam, t_fnum=t_fnum, t_mmat=t_mmat).values()
            if not t_diam or not t_type or not t_fnum or not t_mmat:
                raise Exception("請填寫完整")
            t_msg = TbDesignmessage.objects.filter(t_type=t_type, t_diam=t_diam, t_fnum=t_fnum, t_mmat=t_mmat).values()
            content['payload'] = t_msg
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def copy_wheel(request, pk):
    if request.method == "POST":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            now = datetime.datetime.now()
            data = request.data
            if data:
                w_msg = TbWheelmessage.objects.filter(toolt_id=pk, m_type=data['from']).values()
                if w_msg:
                    for i in w_msg:
                        w_msg = TbWheelmessage()
                        w_msg.t_name = i['t_name']
                        w_msg.t_ver = i['t_ver']
                        w_msg.w_no = i["w_no"]  # 砂輪序號
                        w_msg.w_type = i["w_type"]  # 砂輪型號
                        w_msg.w_feed = i["w_feed"]  # 砂輪粒度
                        w_msg.w_speed = i["w_speed"]  # 砂輪轉速
                        w_msg.w_gran = i["w_gran"]  # 砂輪進給
                        w_msg.m_type = data["to"]  # 機台型號
                        w_msg.w_station = i["w_station"]  # 砂輪磨削工位
                        w_msg.toolt_id = pk
                        w_msg.desi_id = request.user
                        w_msg.last_name=request.user.last_name
                        w_msg.desi_time = now
                        w_msg.save()
                    content['payload'] = "OK"
                else:
                    content["errmsg"] = "沒有找到需要複製的砂輪"
                    content['payload'] = 1
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            #data = request.data
            m_type= request.GET.get('m_type', None)
            if not m_type:
                raise Exception("請傳入機台型號 'm_type' !")
            TbWheelmessage.objects.filter(toolt=pk,m_type=m_type).delete()
            content['payload'].append("OK")
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)



@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def copy_wheel_sort(request, pk):
    if request.method == "POST":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            now = datetime.datetime.now()
            data = request.data
            my_uuid = uuid.uuid4()
            if data['from'] and data['to'] and data['uuid']:
                w_sort_msg = TbWheelSort.objects.filter(toolt_id=pk, m_no=data['from'],uuid=data['uuid']).values()
                if w_sort_msg:
                    for i in w_sort_msg:
                        w_sort_msg = TbWheelSort()
                        w_sort_msg.t_name = i['t_name']
                        w_sort_msg.w_no = i['w_no']
                        w_sort_msg.m_no = data['to']

                        w_sort_msg.w_name = i["w_name"]
                        w_sort_msg.w_ceme = i["w_ceme"]
                        w_sort_msg.w_bran = i["w_bran"]
                        w_sort_msg.w_diam = i["w_diam"]

                        w_sort_msg.w_arc = i["w_arc"]
                        w_sort_msg.m_stat = i["m_stat"]
                        w_sort_msg.engi_id = i["engi_id"]
                        w_sort_msg.update_time = now

                        w_sort_msg.t_ver = i["t_ver"]
                        w_sort_msg.status = i["status"]
                        w_sort_msg.w_rnot1 = i["w_rnot1"]
                        w_sort_msg.w_rnot2 = i["w_rnot2"]
                        w_sort_msg.w_gran = i["w_gran"]
                        w_sort_msg.w_station= i["w_station"]
                        w_sort_msg.toolt_id = pk
                        w_sort_msg.mark_num=1
                        w_sort_msg.uuid=my_uuid

                        w_sort_msg.save()
                    content['payload'] = "OK"
                else:
                    content["errmsg"] = "沒有找到需要複製的砂輪历史信息"
                    content['payload'] = 1
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)



@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def data_nav(request):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            machine = []
            result={}
            site = request.GET.get('site', '')
            org = request.GET.get('org', '')
            m_type = request.GET.get('m_type','')
            result = TbMachine.objects.values('site').distinct()
            if site and not org:
                result = TbMachine.objects.filter(site=site).values('org').distinct()
            elif site and org and not m_type:
                result = TbMachine.objects.filter(site=site, org=org).values(
                    'm_type').distinct().order_by('m_type')
            elif site and org and m_type:
                result = TbMachine.objects.all().filter(site=site, org=org, m_type=m_type).order_by('new_name')
            if m_type:
                for i in result:
                    result1 = {}
                    result1={'m_no':i.site + '-' + i.m_type + '-' + ('00' + i.cell_num)[-3:]}
                    #machine.append(i.site + '-' + i.m_type + '-' + ('00' + i.cell_num)[-3:])
                    machine.append(result1)
                result = machine
            content['payload'] = result
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def export_data(request):
    if request.method == "GET":
        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            where = []
            sql_where = ''
            pr_sql = "SELECT a.t_name,a.t_ver,e.t_type,a.m_no,d.site,d.org,c.d_code,c.g_size,c.g_otol,\
                      c.g_itol,b.ct,a.me_no,a.t_no,a.t_rnot,a.t_bmta,a.me_num, \
                      a.wheel_1,a.wheel_2,a.wheel_3,a.p_para,a.op_id,a.op_time \
                      FROM `tb_productionmessage` a LEFT JOIN tb_product_head b ON a.head_id = b.id \
                      LEFT JOIN tb_designsize c ON b.toolt_id = c.toolt_id \
                      AND a.d_code = c.d_code LEFT JOIN tb_machine d ON a.m_no=d.new_name  \
                      LEFT JOIN tb_designmessage e ON b.toolt_id=e.id  WHERE a.head_id IS NOT NULL {}"
            site = request.GET.get('site', '')
            org = request.GET.get('org', '')
            t_name = request.GET.get('t_name', '')
            t_type = request.GET.get('t_type', '')
            m_no = request.GET.get('m_no', '')
            m_type = request.GET.get('m_type', '')
            status = request.GET.get('status', '')
            str_time = request.GET.get('str_time', '')
            end_time = request.GET.get('end_time', '')
            op_id = request.GET.get('op_id', '')
            d_code = request.GET.get('size_code', '')

            page_num = request.GET.get("page", None)


            where.append('1=1')
            if site:
                where.append('d.site="{}"'.format(site))
            if org:
                where.append('d.org="{}"'.format(org))
            if t_name:
                where.append('a.t_name="{}"'.format(t_name))
            if t_type:
                where.append('e.t_type="{}"'.format(t_type))
            if m_no:
                where.append('a.m_no="{}"'.format(m_no))
            if m_type:
                where.append('d.m_type="{}"'.format(m_type))
            if status:
                where.append('a.status="{}"'.format(status))
            if str_time:
                where.append('date(a.op_time)>="{}"'.format(str_time))
            if end_time:
                where.append('date(a.op_time)<="{}"'.format(end_time))
            if op_id:
                where.append('a.op_id="{}"'.format(op_id))
            if d_code:
                where.append('a.d_code="{}"'.format(d_code))
            if where:
                for i in where:
                    sql_where += ' AND {}'.format(i)
            data = conn_ims(pr_sql.format(sql_where))
            data1 = []
            for i in data:
                result = {}
                result['t_name']=i[0]
                result['t_ver'] = i[1]
                result['t_type'] = i[2]
                result['m_no'] = i[3]
                result['site'] = i[4]
                result['org'] = i[5]
                result['d_code'] = i[6]
                result['g_size'] = i[7]
                result['g_otol'] = i[8]
                result['g_itol'] = i[9]
                result['ct'] = i[10]
                result['me_no'] = i[11]
                result['t_no']=i[12]
                result['t_rnot'] = i[13]
                result['t_bmta'] = i[14]
                result['me_num'] = i[15]
                result['wheel_1'] = i[16]
                result['wheel_2'] = i[17]
                result['wheel_3'] = i[18]
                result['p_para'] = i[19]
                result['op_id'] = i[20]
                result['op_time'] = i[21] and i[21].strftime("%Y-%m-%d %H:%M:%S") or i[21]
                data1.append(result)
            data = data1


            if page_num:
                pag_class = Paginator(data, 20)
            else:
                pag_class = Paginator(data, len(data) + 1)
                page_num = 1
            select_data = pag_class.page(page_num)


            content["payload"] = {"data": [], "page": {}}
            if select_data:
                for i in select_data:
                    #i["desi_time"] = i["desi_time"].strftime("%Y-%m-%d %H:%M:%S")
                    content["payload"]["data"].append(i)
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}

            #print(select_data)

            #content['payload'] = data
        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return Response(content)


# @api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
# def correct_data(request):
#     if request.method == "GET":
#         response=''
#         content = {"payload": [], "status": 0, "errmsg": ''}
#         try:
#
#             where = []
#             header = ['刀具名稱', '版本', '刀具類型', '機台編號', '廠區', '單位名稱',
#                       '尺寸代碼', '磨削尺寸', '上公差', '下公差', 'CT', '測量序列',
#                       '刀具流水號', '裝夾跳動', '刀具基材', '檢測值', '砂輪1補正', '砂輪2補正',
#                       '砂輪3補正', '程序補正', '工號', '記錄時間']
#             sql_where = ''
#             pr_sql = "SELECT a.t_name,a.t_ver,e.t_type,a.m_no,d.site,d.org,c.d_code,c.g_size,c.g_otol,\
#                               c.g_itol,b.ct,a.me_no,a.t_no,a.t_rnot,a.t_bmta,a.me_num, \
#                               a.wheel_1,a.wheel_2,a.wheel_3,a.p_para,a.op_id,a.op_time \
#                               FROM `tb_productionmessage` a LEFT JOIN tb_product_head b ON a.head_id = b.id \
#                               LEFT JOIN tb_designsize c ON b.toolt_id = c.toolt_id \
#                               AND a.d_code = c.d_code LEFT JOIN tb_machine d ON a.m_no=d.new_name  \
#                               LEFT JOIN tb_designmessage e ON b.toolt_id=e.id  WHERE a.head_id IS NOT NULL {}"
#             site = request.GET.get('site', '')
#             org = request.GET.get('org', '')
#             t_name = request.GET.get('t_name', '')
#             t_type = request.GET.get('t_type', '')
#             m_no = request.GET.get('m_no', '')
#             m_type = request.GET.get('m_type', '')
#             status = request.GET.get('status', '')
#             str_time = request.GET.get('str_time', '')
#             end_time = request.GET.get('end_time', '')
#             op_id = request.GET.get('op_id', '')
#             d_code = request.GET.get('size_code', '')
#             where.append('1=1')
#             if site:
#                 where.append('d.site="{}"'.format(site))
#             if org:
#                 where.append('d.org="{}"'.format(org))
#             if t_name:
#                 where.append('a.t_name="{}"'.format(t_name))
#             if t_type:
#                 where.append('e.t_type="{}"'.format(t_type))
#             if m_no:
#                 where.append('a.m_no="{}"'.format(m_no))
#             if m_type:
#                 where.append('d.m_type="{}"'.format(m_type))
#             if status:
#                 where.append('a.status="{}"'.format(status))
#             if str_time:
#                 where.append('date(a.op_time)>="{}"'.format(str_time))
#             if end_time:
#                 where.append('date(a.op_time)<="{}"'.format(end_time))
#             if op_id:
#                 where.append('a.op_id="{}"'.format(op_id))
#             if d_code:
#                 where.append('a.d_code="{}"'.format(d_code))
#             if where:
#                 for i in where:
#                     sql_where += ' AND {}'.format(i)
#             data = conn_ims(pr_sql.format(sql_where))
#             # objs = TbProducttivity.objects.all()
#             # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
#             wb = xlwt.Workbook(encoding='utf-8')
#             ws = wb.add_sheet('補正數據')
#             style_k1 = xlwt.easyxf(
#                 'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
#             style_k = xlwt.easyxf(
#                 'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
#             for i in range(0, len(header)):
#                 ws.col(i).width = 256 * 15  # around 220 pixels
#             for rx in range(0, 1):
#                 for cx in range(0, len(header)):
#                     ws.write(rx, cx, header[cx], style_k1)
#             excel_row = 1
#             for obj in data:
#                 for i in range(0, len(header)):
#                     if i == 21:
#                         ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
#                     else:
#                         ws.write(excel_row, i, obj[i], style_k)
#                 excel_row = excel_row + 1
#             # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
#             response = HttpResponse(content_type='application/vnd.ms-excel')
#             response['Content-Disposition'] = 'attachment; filename=data.xls'
#             wb.save(response)
#         except Exception as e:
#             content["status"] = 1
#             content["errmsg"] = str(e)
#         finally:
#             return response





# @api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
# def wheel_correct_data(request):
#     if request.method == "GET":
#
#         # start_time = request.GET.get("start_time", None)
#         # wheel_down(start_time)
#         content = {"payload": [], "status": 0, "errmsg": ''}
#         str_time = request.GET.get("str_time", None)
#         end_time = request.GET.get("end_time", None)
#         try:
#             header = ['刀具名稱', '版次','刀具類型','機台編號','單位名稱',
#                       '砂輪序號',  '砂輪類型', '砂輪粒度','磨削工位','砂輪編號',
#                       '砂輪品牌', '砂輪直徑', '砂輪R角', '徑向跳動','工號',
#                        '姓名','修改時間','m_stat','完工時間','文件名稱','uuid']
#
#             pr_sql = "SELECT a.t_name,a.t_ver,c.t_type,a.m_no,b.org,\
#                              a.w_no,a.w_ceme,a.w_gran,a.w_station,a.w_name,\
#                              a.w_bran,a.w_diam,a.w_arc,a.w_rnot1,a.engi_id,\
#                              a.last_name,a.update_time,a.m_stat,a.end_time,a.file_path0,a.uuid FROM \
#                              (SELECT * FROM tb_wheel_sort WHERE DATE(update_time)>='{0}' AND DATE(update_time)<='{1}') a ,\
#                              (SELECT new_name,org FROM tb_machine) b ,\
#                              (SELECT t_name,t_type,t_ver FROM tb_designmessage ) c \
#                              WHERE a.m_no=b.new_name AND a.t_name=c.t_name AND a.t_ver=c.t_ver".format(str_time,end_time)
#
#             data = conn_ims(pr_sql)
#             # objs = TbProducttivity.objects.all()
#             # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
#             wb = xlwt.Workbook(encoding='utf-8')
#             ws = wb.add_sheet('砂輪數據')
#             style_k1 = xlwt.easyxf(
#                 'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
#             style_k = xlwt.easyxf(
#                 'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
#             for i in range(0, len(header)):
#                 ws.col(i).width = 256 * 15  # around 220 pixels
#             for rx in range(0, 1):
#                 for cx in range(0, len(header)):
#                     ws.write(rx, cx, header[cx], style_k1)
#             excel_row = 1
#             for obj in data:
#                 for i in range(0, len(header)):
#                     if i == 16 or i==18:
#                         ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
#                     else:
#                         ws.write(excel_row, i, obj[i], style_k)
#                 excel_row = excel_row + 1
#             # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
#             response = HttpResponse(content_type='application/vnd.ms-excel')
#             response['Content-Disposition'] = 'attachment; filename=wheel_data.xls'
#             wb.save(response)
#         except Exception as e:
#             content["status"] = 1
#             content["errmsg"] = str(e)
#         finally:
#             return response


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def correct_data(request):
    if request.method == "GET":
        #print(1111)
        response=''
        status = request.GET.get('status', None)

        if not status:
            raise Exception("請傳入下載的類型status！")

        content = {"payload": [], "status": 0, "errmsg": ''}
        try:
            if int(status) == 4 or int(status) == 5:
                #print(454545)
                where = []
                header = ['刀具名稱', '版本', '刀具類型', '機台編號', '廠區', '單位名稱',
                          '尺寸代碼', '磨削尺寸', '上公差', '下公差', 'CT', '測量序列',
                          '刀具流水號', '裝夾跳動', '刀具基材', '檢測值', '砂輪1補正', '砂輪2補正',
                          '砂輪3補正', '程序補正', '工號', '記錄時間','上傳文件路径(/mysite/fileData2/ST/)']

                sql_where = ''
                pr_sql = "SELECT a.t_name,a.t_ver,e.t_type,a.m_no,d.site,d.org,c.d_code,c.g_size,c.g_otol,\
                                  c.g_itol,b.ct,a.me_no,a.t_no,a.t_rnot,a.t_bmta,a.me_num, \
                                  a.wheel_1,a.wheel_2,a.wheel_3,a.p_para,a.op_id,a.op_time,b.file_path \
                                  FROM `tb_productionmessage` a LEFT JOIN tb_product_head b ON a.head_id = b.id \
                                  LEFT JOIN tb_designsize c ON b.toolt_id = c.toolt_id \
                                  AND a.d_code = c.d_code LEFT JOIN tb_machine d ON a.m_no=d.new_name  \
                                  LEFT JOIN tb_designmessage e ON b.toolt_id=e.id  WHERE a.head_id IS NOT NULL {}"
                site = request.GET.get('site', '')
                org = request.GET.get('org', '')
                t_name = request.GET.get('t_name', '')
                t_type = request.GET.get('t_type', '')
                m_no = request.GET.get('m_no', '')
                m_type = request.GET.get('m_type', '')
                #status = request.GET.get('status', '')
                str_time = request.GET.get('str_time', '')
                end_time = request.GET.get('end_time', '')
                op_id = request.GET.get('op_id', '')
                d_code = request.GET.get('size_code', '')
                where.append('1=1')
                if site:
                    where.append('d.site="{}"'.format(site))
                if org:
                    where.append('d.org="{}"'.format(org))
                if t_name:
                    where.append('a.t_name="{}"'.format(t_name))
                if t_type:
                    where.append('e.t_type="{}"'.format(t_type))
                if m_no:
                    where.append('a.m_no="{}"'.format(m_no))
                if m_type:
                    where.append('d.m_type="{}"'.format(m_type))
                if status:
                    where.append('a.status="{}"'.format(status))
                if str_time:
                    where.append('date(a.op_time)>="{}"'.format(str_time))
                if end_time:
                    where.append('date(a.op_time)<="{}"'.format(end_time))
                if op_id:
                    where.append('a.op_id="{}"'.format(op_id))
                if d_code:
                    where.append('a.d_code="{}"'.format(d_code))
                if where:
                    for i in where:
                        sql_where += ' AND {}'.format(i)
                data = conn_ims(pr_sql.format(sql_where))

                #print(data)
                # objs = TbProducttivity.objects.all()
                # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
                wb = xlwt.Workbook(encoding='utf-8')
                ws = wb.add_sheet('補正數據')
                style_k1 = xlwt.easyxf(
                    'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
                style_k = xlwt.easyxf(
                    'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
                for i in range(0, len(header)):
                    ws.col(i).width = 256 * 15  # around 220 pixels
                for rx in range(0, 1):
                    for cx in range(0, len(header)):
                        ws.write(rx, cx, header[cx], style_k1)
                excel_row = 1
                for obj in data:
                    for i in range(0, len(header)):
                        if i == 21:
                            ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
                        elif i==22 and obj[i]:
                            ws.write(excel_row, i, '/mysite/fileData2/ST/'+obj[i].split('/')[2], style_k)
                        else:
                            ws.write(excel_row, i, obj[i], style_k)
                    excel_row = excel_row + 1
                # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition'] = 'attachment; filename=data.xls'
                wb.save(response)



            elif int(status)==1:                                      #刀具信息（尺寸）数据导出
                # print(111.1111)
                where = []
                header = ['刀具名稱', '版次','刀具規格','刀具類型','刀具刃長',
                          '刀具直徑',  '刀具刃數', '加工材質','尺寸代碼','代碼名稱',
                          '研磨方式', '磨削尺寸', '上公差', '下公差','工號',
                          '姓名','修改時間']
                sql_where = ''
                pr_sql = "SELECT a.t_name,a.t_ver,a.t_spec,a.t_type,a.t_diam,a.t_flen,a.t_fnum,a.t_mmat,\
                          b.d_code,b.grindingsite,b.g_type,b.g_size,b.g_otol,b.g_itol,b.desi_id,b.last_name,b.desi_time FROM \
                          (SELECT * FROM tb_designmessage) a,\
                          (SELECT * FROM `tb_designsize`) b\
                          WHERE a.t_name=b.t_name AND a.t_ver=b.t_ver {} "

                t_name = request.GET.get('t_name', '')
                t_type = request.GET.get('t_type', '')
                str_time = request.GET.get('str_time', '')
                end_time = request.GET.get('end_time', '')

                where.append('1=1')

                if t_name:
                    where.append('a.t_name="{}"'.format(t_name))
                if t_type:
                    where.append('a.t_type="{}"'.format(t_type))
                if str_time and end_time:
                    if end_time>=str_time:
                        where.append('date(b.desi_time)>="{}"'.format(str_time))
                        where.append('date(b.desi_time)<="{}"'.format(end_time))
                    else:
                        raise Exception(u"開始時間不能大於結束時間")
                else:
                    end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
                    str_time = (datetime.datetime.now() + datetime.timedelta(days=-20)).strftime('%Y-%m-%d %H:%M')

                    where.append('date(b.desi_time)>="{}"'.format(str_time))
                    where.append('date(b.desi_time)<="{}"'.format(end_time))

                if where:
                    for i in where:
                        sql_where += ' AND {}'.format(i)
                # print(pr_sql.format(sql_where))
                data = conn_ims(pr_sql.format(sql_where))
                # print(data)
                #data = conn_ims(pr_sql)
                # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
                wb = xlwt.Workbook(encoding='utf-8')
                ws = wb.add_sheet('刀具尺寸信息')
                style_k1 = xlwt.easyxf(
                    'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
                style_k = xlwt.easyxf(
                    'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
                for i in range(0, len(header)):
                    ws.col(i).width = 256 * 15  # around 220 pixels
                for rx in range(0, 1):
                    for cx in range(0, len(header)):
                        ws.write(rx, cx, header[cx], style_k1)
                excel_row = 1
                for obj in data:
                    for i in range(0, len(header)):
                        if  i == 16:
                            ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
                        else:
                            ws.write(excel_row, i, obj[i], style_k)
                    excel_row = excel_row + 1
                # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
                # print(101010)
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition1'] = 'attachment; filename=data.xls'
                wb.save(response)
                # print(99999)


            elif int(status)==2:                                      #刀具信息（砂轮）数据导出
                # print(222.222)
                where = []
                header = ['刀具名稱', '版次','刀具規格','刀具類型','刀具刃長',
                          '刀具直徑',  '刀具刃數', '加工材質','機型','砂輪序號',
                          '砂輪類型', '砂輪粒度', '砂輪轉速', '砂輪進給','磨削工位',
                          '工號','姓名','修改時間']
                sql_where = ''
                pr_sql = "SELECT a.t_name,a.t_ver,b.t_spec ,b.t_type,b.t_diam,b.t_flen,b.t_fnum,b.t_mmat,\
                          a.m_type,a.w_no,a.w_type,a.w_gran,a.w_speed,a.w_feed,a.w_station,a.desi_id ,a.last_name,a.desi_time FROM \
                          (SELECT * FROM tb_wheelmessage) a,\
                          (SELECT * FROM tb_designmessage) b \
                          WHERE a.t_name=b.t_name AND a.t_ver=b.t_ver {} "

                t_name = request.GET.get('t_name', '')
                t_type = request.GET.get('t_type', '')
                str_time = request.GET.get('str_time', '')
                end_time = request.GET.get('end_time', '')

                where.append('1=1')

                if t_name:
                    where.append('a.t_name="{}"'.format(t_name))
                if t_type:
                    where.append('b.t_type="{}"'.format(t_type))
                if str_time and end_time:
                    if end_time>=str_time:
                        where.append('date(a.desi_time)>="{}"'.format(str_time))
                        where.append('date(a.desi_time)<="{}"'.format(end_time))
                    else:
                        raise Exception(u"開始時間不能大於結束時間")
                else:
                    end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
                    str_time = (datetime.datetime.now() + datetime.timedelta(days=-7)).strftime('%Y-%m-%d %H:%M')

                    where.append('date(a.desi_time)>="{}"'.format(str_time))
                    where.append('date(a.desi_time)<="{}"'.format(end_time))

                if where:
                    for i in where:
                        sql_where += ' AND {}'.format(i)
                # print(pr_sql.format(sql_where))
                data = conn_ims(pr_sql.format(sql_where))
                # print(data)
                #data = conn_ims(pr_sql)
                # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
                wb = xlwt.Workbook(encoding='utf-8')
                ws = wb.add_sheet('刀具砂輪信息')
                style_k1 = xlwt.easyxf(
                    'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
                style_k = xlwt.easyxf(
                    'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
                for i in range(0, len(header)):
                    ws.col(i).width = 256 * 15  # around 220 pixels
                for rx in range(0, 1):
                    for cx in range(0, len(header)):
                        ws.write(rx, cx, header[cx], style_k1)
                excel_row = 1
                for obj in data:
                    for i in range(0, len(header)):
                        if  i == 17:
                            ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
                        else:
                            ws.write(excel_row, i, obj[i], style_k)
                    excel_row = excel_row + 1
                # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
                # print(101010)
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition1'] = 'attachment; filename=designmessage_wheel_data.xls'
                wb.save(response)


            elif int(status)==3:                                      #砂轮修整数据导出
                # print(2222)
                where = []
                header = ['刀具名稱', '版次','刀具類型','機台編號','單位名稱',
                          '砂輪序號',  '砂輪類型', '砂輪粒度','磨削工位','砂輪編號',
                          '砂輪品牌', '砂輪直徑', '砂輪R角', '徑向跳動','工號',
                          '姓名','修改時間','加工狀態','完工時間','文件名稱','uuid']
                sql_where = ''
                pr_sql = "SELECT a.t_name,a.t_ver,c.t_type,a.m_no,b.org,\
                                 a.w_no,a.w_ceme,a.w_gran,a.w_station,a.w_name,\
                                 a.w_bran,a.w_diam,a.w_arc,a.w_rnot1,a.engi_id,\
                                 a.last_name,a.update_time,a.m_stat,a.end_time,a.file_path0,a.uuid FROM \
                                 (SELECT * FROM tb_wheel_sort ) a ,\
                                 (SELECT new_name,org FROM tb_machine) b ,\
                                 (SELECT t_name,t_type,t_ver FROM tb_designmessage ) c\
                                 WHERE a.m_no=b.new_name AND a.t_name=c.t_name AND a.t_ver=c.t_ver {} "

                site = request.GET.get('site', '')
                org = request.GET.get('org', '')
                m_type = request.GET.get('m_type', '')
                m_no = request.GET.get('m_no', '')
                t_name = request.GET.get('t_name', '')
                t_type = request.GET.get('t_type', '')
                str_time = request.GET.get('str_time', '')
                end_time = request.GET.get('end_time', '')

                #print(end_time)

                where.append('1=1')
                if site:
                    where.append('a.m_no LIKE"{}%"'.format(site))
                if org:
                    where.append('b.org="{}"'.format(org))
                if m_type:
                    where.append('a.m_no LIKE"%{}%"'.format(m_type))
                if m_no:
                    where.append('a.m_no="{}"'.format(m_no))
                if t_name:
                    where.append('a.t_name="{}"'.format(t_name))
                if t_type:
                    where.append('c.t_type="{}"'.format(t_type))
                if str_time and end_time:
                    if end_time>=str_time:
                        where.append('date(a.update_time)>="{}"'.format(str_time))
                        where.append('date(a.update_time)<="{}"'.format(end_time))
                    else:
                        raise Exception(u"開始時間不能大於結束時間")
                else:
                    end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
                    str_time = (datetime.datetime.now() + datetime.timedelta(days=-7)).strftime('%Y-%m-%d %H:%M')

                    where.append('date(a.update_time)>="{}"'.format(str_time))
                    where.append('date(a.update_time)<="{}"'.format(end_time))

                if where:
                    for i in where:
                        sql_where += ' AND {}'.format(i)
                #print(pr_sql.format(sql_where))
                data = conn_ims(pr_sql.format(sql_where))
                # print(data)
                # print(777)
                #data = conn_ims(pr_sql)
                # objs = TbProducttivity.objects.all()
                # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
                wb = xlwt.Workbook(encoding='utf-8')
                ws = wb.add_sheet('砂輪修整數據')
                style_k1 = xlwt.easyxf(
                    'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
                style_k = xlwt.easyxf(
                    'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
                for i in range(0, len(header)):
                    ws.col(i).width = 256 * 15  # around 220 pixels
                for rx in range(0, 1):
                    for cx in range(0, len(header)):
                        ws.write(rx, cx, header[cx], style_k1)
                excel_row = 1
                for obj in data:
                    for i in range(0, len(header)):
                        if  i == 16 or i==18:
                            ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
                        else:
                            ws.write(excel_row, i, obj[i], style_k)
                    excel_row = excel_row + 1
                # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
                # print(101010)
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition1'] = 'attachment; filename=data.xls'
                wb.save(response)


            elif int(status) == 6:                         # 调磨削条件数据导出
                # print(2222)
                where = []
                header = ['刀具名稱', '版次', '刀具類型', '機台編號', '單位名稱',
                          '砂輪序號', '砂輪類型', '砂輪粒度', '砂輪直徑', '砂輪R角',
                          '動平衡', '實際轉速', '實際進給', '調磨削序號', '工號',
                          '姓名', '修改時間', '加工狀態', '完工時間', 'uuid']
                sql_where = ''
                pr_sql = "SELECT a.t_name,a.t_ver,b.t_type,a.m_no, c.org,d.w_no,d.w_ceme,d.w_gran,d.w_diam,d.w_arc,\
                          a.w_bala,a.w_speed,a.w_feed,a.ap_num,a.engi_id,a.last_name,a.update_time,a.m_stat,a.end_time,d.uuid FROM \
                          (SELECT * FROM tb_ablation)a,\
                          (SELECT t_name,t_type,t_ver FROM tb_designmessage) b,\
                          (SELECT new_name,org FROM tb_machine)c,\
                          (SELECT id,w_no,w_ceme,w_gran,w_diam,w_arc,uuid FROM tb_wheel_sort) d \
                          WHERE  a.t_name=b.t_name AND a.t_ver=b.t_ver \
                          AND a.m_no=c.new_name AND a.wsort_id=d.id {} "

                site = request.GET.get('site', '')
                org = request.GET.get('org', '')
                m_type = request.GET.get('m_type', '')
                m_no = request.GET.get('m_no', '')
                t_name = request.GET.get('t_name', '')
                t_type = request.GET.get('t_type', '')
                str_time = request.GET.get('str_time', '')
                end_time = request.GET.get('end_time', '')

                # print(end_time)

                where.append('1=1')
                if site:
                    where.append('a.m_no LIKE"{}%"'.format(site))
                if org:
                    where.append('c.org="{}"'.format(org))
                if m_type:
                    where.append('a.m_no LIKE"%{}%"'.format(m_type))
                if m_no:
                    where.append('a.m_no="{}"'.format(m_no))
                if t_name:
                    where.append('a.t_name="{}"'.format(t_name))
                if t_type:
                    where.append('b.t_type="{}"'.format(t_type))
                if str_time and end_time:
                    if end_time >= str_time:
                        where.append('date(a.update_time)>="{}"'.format(str_time))
                        where.append('date(a.update_time)<="{}"'.format(end_time))
                    else:
                        raise Exception(u"開始時間不能大於結束時間")
                else:
                    end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
                    str_time = (datetime.datetime.now() + datetime.timedelta(days=-7)).strftime('%Y-%m-%d %H:%M')

                    where.append('date(a.update_time)>="{}"'.format(str_time))
                    where.append('date(a.update_time)<="{}"'.format(end_time))

                if where:
                    for i in where:
                        sql_where += ' AND {}'.format(i)
                # print(pr_sql.format(sql_where))
                data = conn_ims(pr_sql.format(sql_where))
                # print(data)
                # print(777)
                # data = conn_ims(pr_sql)
                # objs = TbProducttivity.objects.all()
                # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
                wb = xlwt.Workbook(encoding='utf-8')
                ws = wb.add_sheet('砂輪數據')
                style_k1 = xlwt.easyxf(
                    'font: bold on,colour_index black,height 200;borders:left 1,right 1,top 1,bottom 1;pattern: pattern alt_bars, fore_colour yellow, back_colour yellow')
                style_k = xlwt.easyxf(
                    'borders:left 1, right 1, top 1, bottom 1; pattern: pattern solid, fore_colour ivory')
                for i in range(0, len(header)):
                    ws.col(i).width = 256 * 15  # around 220 pixels
                for rx in range(0, 1):
                    for cx in range(0, len(header)):
                        ws.write(rx, cx, header[cx], style_k1)
                excel_row = 1
                for obj in data:
                    for i in range(0, len(header)):
                        if i == 16 or i == 18:
                            ws.write(excel_row, i, obj[i] and str(obj[i]) or obj[i], style_k)
                        else:
                            ws.write(excel_row, i, obj[i], style_k)
                    excel_row = excel_row + 1
                # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
                # print(101010)
                response = HttpResponse(content_type='application/vnd.ms-excel')
                response['Content-Disposition1'] = 'attachment; filename=data.xls'
                wb.save(response)


        except Exception as e:
            content["status"] = 1
            content["errmsg"] = str(e)
        finally:
            return response
